/**
 * Created by MorenYang on 2017/12/8.
 */

const AUTH_USER_FLAG = 'UML_USER';
const AUTH_USER_TYPE = 'UML_USER_TYPE';
const AUTH_TOKEN_FLAG = 'UML_TOKEN';

const auth = (state = getAuthStaus(), action) => {
  switch (action.type) {
    case 'USER_LOGIN': {
      setUser(action);
      setToken(action);
      return getAuthStaus();
    }
    case 'SET_USER': {
      setUser(action);
      return getAuthStaus();
    }
    case 'USER_LOGOUT': {
      clearAuthState();
      return getAuthStaus();
    }
    default:
      return state;
  }
};

export default auth;

const setUser = ({user, userType}) => {
  localStorage.setItem(AUTH_USER_FLAG, JSON.stringify(user));
  localStorage.setItem(AUTH_USER_TYPE, userType);
};

const setToken = ({token}) => {
  localStorage.setItem(AUTH_TOKEN_FLAG, token);
};

const clearAuthState = () => {
  localStorage.removeItem(AUTH_TOKEN_FLAG);
  localStorage.removeItem(AUTH_USER_FLAG);
  localStorage.removeItem(AUTH_USER_TYPE)
};

const getAuthStaus = () => {
  let user = null, token = null, userType = null, authStatus = !!localStorage.getItem(AUTH_TOKEN_FLAG);
  if (authStatus) {
    token = localStorage.getItem(AUTH_TOKEN_FLAG);
    user = JSON.parse(localStorage.getItem(AUTH_USER_FLAG));
    userType = localStorage.getItem(AUTH_USER_TYPE);
  }
  return {user, token, userType, authStatus}
};

